const express = require("express");
const bodyParser = require("body-parser");
const uploader = require("express-fileupload");
const {extname, resolve} = require('path')
const {existsSync, appendFileSync, writeFileSync} = require('fs')
const app = express();
const PORT = 8000;

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(uploader());
app.use('/', express.static('files_temp'))

const AllOWED_TYPE = {
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
  'application/pdf': 'pdf'
}

//设置跨域
app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-origin", "*");
  res.header("Access-Control-Allow-Methods", "POST,GET");
  next();
});

app.post("/upload_video", (req, res) => {
  // res.send({
  //   msg: "获取参数成功",
  //   code: 200,
  // });
  console.log(req.body)
  const {name, type, size, fileName, uploadedSize} = req.body;
  const {file} = req.files;
  if (!file) {
    res.send({
      code: 1001,
      msg: 'No file uploaded'
    })
    return
  }
  if (!AllOWED_TYPE[type]) {
    res.send({
      code: 1002,
      msg: 'The type is not allowed for Uploading'
    })
    return;
  }
  const filename = fileName + extname(name)
  const filePath = resolve(__dirname, './files_temp' + fileName)
  if (uploadedSize !== "0") {
    if (!existsSync(filePath)) {
      res.send({
        code: 1003,
        msg: 'No file Exists'
      });
      return;
    }
    appendFileSync(filePath, file.data);
    res.send({
      code: 200,
      msg: 'Appended'
    })
    return;
  }
  writeFileSync(filePath, file.data)
  res.send({
    code: 0,
    msg: "File is created",
    data: {
      src: 'http://localhost:8000' + fileName
    }
  })
});

app.listen(PORT, () => {
  console.log(`Serve runing at ${PORT} ······`);
});
